package org.kjk.board;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.kjk.common.DAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Component;

@Component("boardDao")
public class BoardDAOImpl implements DAO {

	@Autowired
	@Qualifier("jdbcTemplate")
	public JdbcTemplate jdbcTemplate;

	@Override
	public <T> int insert(T obj) {
		String sql = "insert into board(SERIAL, SUBJECT, CONTENT, WRITER) values((select max(serial) + 1 from board), ?, ?, ?)";
		BoardDTO dto = (BoardDTO) obj;
		return jdbcTemplate.queryForInt(sql, dto.getData());
	}

	@Override
	public <T> int update(T obj) {
		String sql = "update board set SUBJECT=?, CONTENT=?, WRITER=? where SERIAL=?";
		BoardDTO dto = (BoardDTO) obj;
		Object[] param = new Object[dto.getData().length + 1];
		for (int i = 0; i < dto.getData().length; i++) {
			param[i] = dto.getData()[i];
		}
		param[param.length - 1] = dto.getSerial();
		return jdbcTemplate.queryForInt(sql, param);
	}

	@Override
	public <T> int delete(T obj) {
		String sql = "delete from board where SERIAL=?";
		BoardDTO dto = (BoardDTO) obj;
		return jdbcTemplate.queryForInt(sql, new Object[] { dto.getSerial() });
	}

	@Override
	public int deleteAll() {
		String sql = "delete from board";
		return jdbcTemplate.queryForInt(sql);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BoardDTO> select(String sql, String[] param) {
		return jdbcTemplate.query(sql, param, new BoardRowMapper());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BoardDTO> selectAll() {
		return jdbcTemplate.query("select * from board", new BoardRowMapper());
	}

	@Override
	public JSONObject selectJson(String sql, String[] param)
			throws JSONException {
		JSONObject json = new JSONObject();
		final JSONArray array = new JSONArray();
		json.put("result", array);
		jdbcTemplate.query(sql, param, new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				JSONObject obj1 = new JSONObject();
				try {
					obj1.put("serial", rs.getInt("SERIAL"));
					obj1.put("subject", rs.getString("SUBJECT"));
					obj1.put("content", rs.getString("CONTENT"));
					obj1.put("writer", rs.getString("WRITER"));
					obj1.put("writtenDate", rs.getString("WRITTENDATE"));
					array.put(obj1);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
		return json;
	}

}
